package org.springcloud.plugin.framework.listener.register;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springcloud.plugin.common.entity.HostFilterEntity;
import org.springcloud.plugin.common.entity.HostFilterType;
import org.springcloud.plugin.common.entity.RegisterEntity;
import org.springcloud.plugin.common.entity.RuleEntity;
import org.springcloud.plugin.framework.listener.BasicListener;
import org.springframework.cloud.client.serviceregistry.Registration;

import java.util.List;

/**
 * author: yanggld
 * date: 2019/12/14 11:49
 * version: 1.0
 * description: 主机信息 注册监听
 */
@Slf4j
public class HostFilterRegisterListener extends BasicListener implements RegisterListener{


    @Override
    public void onRegister(Registration registration) {
        String serviceId = coreAdapter.getServiceId();
        String host = coreAdapter.getHost();
        int port = coreAdapter.getPort();
        applyHostFilter(serviceId, host, port);
    }

    private void applyHostFilter(String serviceId, String host, int port) {
        RuleEntity ruleEntity = coreAdapter.getRule();
        if (ruleEntity == null) {
            return;
        }
        RegisterEntity registerEntity = ruleEntity.getRegisterEntity();
        if (registerEntity == null) {
            return;
        }
        HostFilterEntity hostFilterEntity = registerEntity.getHostFilterEntity();
        if (hostFilterEntity == null) {
            return;
        }
        HostFilterType filterType = hostFilterEntity.getFilterType();
        List<String> globalFilterValueList = hostFilterEntity.getFilterValueList();
        if (CollectionUtils.isEmpty(globalFilterValueList)) {
            return;
        }
        switch (filterType) {
            case WHITELIST:
                validateWhitelist(filterType, globalFilterValueList, serviceId, host, port);
                break;
        }
    }

    private void validateWhitelist(HostFilterType filterType, List<String> allFilterValueList, String serviceId, String host, int port) {
        boolean matched = true;
        for (String filterValue : allFilterValueList) {
            if (host.startsWith(filterValue)) {
                matched = false;
                break;
            }
        }
        if (matched) {
            String description =  " 服务{ "+serviceId+"[ " + host + ":" + port + " ] }被禁止注册！,IP不符合 " + filterType + ":" + allFilterValueList;
            throw new RuntimeException(description);
        }
    }

    @Override
    public void onDeregister(Registration registration) {
        log.info("--------------------------注册下线！！！");
        log.info("--------------------------注册下线！！！");
        log.info("--------------------------注册下线！！！");
    }

    @Override
    public void onSetStatus(Registration registration, String status) {

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
